package com.taurus.myboard.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.taurus.myboard.entity.Menu;
import com.taurus.myboard.entity.RoleMenu;
import com.taurus.myboard.entity.User;
import com.taurus.myboard.entity.UserRole;
import com.taurus.myboard.mapper.MenuMapper;
import com.taurus.myboard.mapper.UserMapper;
import com.taurus.myboard.mapper.UserRoleMapper;
import com.taurus.myboard.service.IMenuService;
import com.taurus.myboard.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taurus.myboard.utils.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kanten
 * @since 2023-06-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private IMenuService menuService;

    @Override
    public Map<String, Object> login(User user) {
        // 根据用户名查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User loginUser = this.baseMapper.selectOne(wrapper);
        // 如果结果不为空，并且密码和传入的密码匹配，则生成token，并将用户信息存入redis
        if (loginUser != null && passwordEncoder.matches(user.getPassword(), loginUser.getPassword())){
            // 暂时使用UUID, TBD:JWT
    //        String key = "user: " + UUID.randomUUID();
            // 存入redis
            loginUser.setPassword(null);//密码TBD
    //        redisTemplate.opsForValue().set(key, loginUser,30, TimeUnit.MINUTES);
            // 使用JWT
            String token = jwtUtil.createToken(loginUser);
            // 返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            return data;
        }
        return null;
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        User loginUser = null;
        try{
            loginUser = jwtUtil.parseToken(token, User.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(loginUser != null){
            Map<String, Object> data =  new HashMap<>();
            data.put("name", loginUser.getUsername());
            data.put("avatar", loginUser.getAvatar());
            // 角色
            List<String> roleList = this.getBaseMapper().getRoleNamesByUserId(loginUser.getId());
            data.put("roles", roleList);
            List<Menu> menuList = menuService.getMenuListByUserId(loginUser.getId());
            data.put("menuList", menuList);

            return data;
        }
        return null;
    }

    @Override
    public void logout(String token) {
//        boolean rst = redisTemplate.delete(token);
    }

    @Override
    @Transactional
    public void addUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.baseMapper.insert(user);
        List<Integer> roleIdList = user.getRoleIdList();
        for (Integer roleId : roleIdList){
            userRoleMapper.insert(new UserRole(user.getId(), roleId));
        }
    }

    @Override
    public User getUserById(Integer id) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId, id);
        User user = this.baseMapper.selectOne(lambdaQueryWrapper);

        LambdaQueryWrapper<UserRole> lambdaQueryWrapperUserRole = new LambdaQueryWrapper<>();
        lambdaQueryWrapperUserRole.eq(UserRole::getUserId, id);
        List<UserRole> userRoleList = userRoleMapper.selectList(lambdaQueryWrapperUserRole);
        List<Integer> roleIdList = userRoleList.stream().map(ur->{
            return ur.getRoleId();
        }).collect(Collectors.toList());
        user.setRoleIdList(roleIdList);
        return user;
    }

    @Override
    public void updateUser(User user) {
        // 更新User
        user.setPassword(null);
        this.baseMapper.updateById(user);
        // 插入rolemenu角色与菜单权限对应表
        if (null != user.getRoleIdList()) {
            this.deleteUserRoleById(user.getId());
            this.insertRoleIdList(user);
        }
    }

    @Override
    public void delUserById(Integer id) {
        // 删除user表
        this.baseMapper.deleteById(id);
        // 删除user role表
        this.deleteUserRoleById(id);
        return;
    }

    private void deleteUserRoleById(Integer id) {
        LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRole::getUserId, id);
        this.userRoleMapper.delete(lambdaQueryWrapper);
    }

    private void insertRoleIdList(User user) {
        // 写入用户与角色对应表
        if (null != user.getRoleIdList()) {
            for (Integer roleId : user.getRoleIdList()) {
                userRoleMapper.insert(new UserRole(user.getId(), roleId));
            }
        }
    }
}
